<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>Chat Interface</title>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
        }

        .chat-title {
            color: #333333;
            font-size: 14px;
        }

        .chat-container {
            height: 100%;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .chat-header {
            background-color: #f2f2f2;
            padding: 10px;
            position: sticky;
            top: 0;
        }

        .chat-content {
            flex-grow: 1;
            overflow-y: auto;
            -ms-overflow-style: none;
            padding: 20px 20px 0;
        }

        .chat-content::-webkit-scrollbar {
            display: none;
        }

        .message {
            margin-bottom: 20px;
        }

        .message .sender {
            font-weight: bold;
            color: #333333;
        }

        .message .content {
            margin-top: 5px;
            padding: 10px;
            background-color: #f2f2f2;
            border-radius: 5px;
            display: inline-block;
            max-width: 80%;
            word-wrap: break-word;
        }

        .user-message {
            text-align: right;
            margin-left: auto;
        }

        .user-message .content {
            line-height: 1.5;
            text-align: left;
            font-size: 14px;
            box-sizing: border-box;
            user-select: text !important;
            padding: 10px 15px;
            background-color: #0a80ff;
            color: #fff;
        }

        .bot-message .content {
            line-height: 1.5;
            text-align: left;
            font-size: 14px;
            box-sizing: border-box;
            user-select: text !important;
            padding: 10px 15px;
            background-color: #e8e8e8;
            color: #333333;
        }

        .chat-footer {
            background-color: #f2f2f2;
            padding: 10px;
            position: sticky;
            bottom: 0;
        }

        .input-container {
            display: flex;
            align-items: center;
        }

        .input-container input[type="text"] {
            flex: 1;
            padding: 10px;
            border: 1px solid #cccccc;
            border-radius: 5px;
        }

        .input-container input[type="submit"] {
            background-color: #0a80ff;
            color: #ffffff;
            border: none;
            padding: 10px 20px;
            margin-left: 10px;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="chat-container">
    <div class="chat-header">
        <span class="chat-title">聊天</span>
    </div>
    <div class="chat-content" id="chat-content">
        <div class="message bot-message">
            <div class="sender">ChatBot</div>
            <div class="content">
                你好！有什么可以帮助您的吗？
            </div>
        </div>
    </div>
    <div class="chat-footer">
        <div class="input-container">
            <input type="text" placeholder="在此输入消息..." id="user-input">
            <input type="submit" value="发送" id="send-button">
        </div>
    </div>
</div>

<script>
    const userInput = document.getElementById('user-input');
    const sendButton = document.getElementById('send-button');
    const chatContent = document.getElementById('chat-content');

    let conversationId = null

    function scrollToBottom() {
        chatContent.scrollTo(0, chatContent.scrollHeight);
    }

    scrollToBottom()

    function addUserMessage(message) {
        const messageElement = document.createElement('div');
        messageElement.classList.add('message', 'user-message');
        messageElement.innerHTML = `<div class="sender">User</div><div class="content">${message}</div>`;
        chatContent.appendChild(messageElement);

        scrollToBottom()
    }

    function addBotMessage(message) {
        const chatMessages = chatContent.getElementsByClassName('message');
        const lastMessage = chatMessages[chatMessages.length - 1];

        if (lastMessage && lastMessage.classList.contains('bot-message')) {
            const contentElement = lastMessage.querySelector('.content');
            const streamedTextElement = document.createElement('span');
            streamedTextElement.classList.add('streamed-text');
            streamedTextElement.innerText = message;
            contentElement.appendChild(streamedTextElement);
        } else {
            const messageElement = document.createElement('div');
            messageElement.classList.add('message', 'bot-message');
            messageElement.innerHTML = `<div class="sender">ChatBot</div><div class="content"><span class="streamed-text">${message}</span></div>`;
            chatContent.appendChild(messageElement);
        }

        scrollToBottom()
    }


    async function getResponse(message) {
        const url = 'https://wetabchat.haohuola.com/api/chat/conversation-v2';

        const headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7InVpZCI6IjY0NDU3YWIzMTBlYjQzZTc1ZTVkODM5MSIsInZlcnNpb24iOjAsInZpcFZlcnNpb24iOjAsImJyYW5jaCI6InpoIn0sImlhdCI6MTY4NjA0MjIzNCwiZXhwIjoxNjg2MjE1MDM0fQ.GaMytPlUSly1vi3Si42c07mi-6P-3MpLtivmE_8fE9Q',
            'Connection': 'keep-alive',
            'Content-Type': 'application/json;charset=UTF-8',
            'Origin': 'chrome-extension://aikflfpejipbpjdlfabpgclhblkpaafo',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'none',
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36',
            'i-app': 'hitab',
            'i-branch': 'zh',
            'i-lang': 'zh-CN',
            'i-platform': 'chrome',
            'i-version': '1.0.49',
            'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
            'sec-ch-ua-mobile': '?1',
            'sec-ch-ua-platform': '"Android"',
        };

        const data = {
            prompt: message,
            conversationId: conversationId
        };

        const requestOptions = {
            method: 'POST',
            headers,
            body: JSON.stringify(data),
        };

        try {
            const response = await fetch(url, requestOptions);
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            const regexContent = /\{"data".*?"成功"\}/g;
            const regexTail = /\{"data".*?"stream done"\}/;

            async function readStream() {
                const {done, value} = await reader.read();
                const decodedValue = decoder.decode(value || new Uint8Array(), {
                    stream: !done,
                });

                if (decodedValue) {
                    const matchContent = decodedValue.match(regexContent);

                    if (matchContent) {
                        let result = "";
                        matchContent.forEach(match => {
                            const {data} = JSON.parse(match);
                            result += data.content;
                        });
                        addBotMessage(result)
                    } else {
                        const matchTail = decodedValue.match(regexTail);

                        if (matchTail) {
                            const dictTail = JSON.parse(matchTail[0]);
                            conversationId = dictTail.data.conversationId
                        }
                    }
                }

                if (done) {
                    console.log("Stream finished");
                } else {
                    return readStream();
                }
            }

            await readStream();
        } catch (error) {
            console.error('请求出错:', error);
        } finally {
            enableInput();
        }
    }

    function disableInput() {
        userInput.disabled = true;
        userInput.placeholder = "等待消息结束";
    }

    function enableInput() {
        userInput.disabled = false;
        userInput.focus();
        userInput.placeholder = "请输入消息，按回车键发送";
    }

    async function sendMessage() {
        const message = userInput.value.trim();
        if (message !== "") {
            userInput.value = "";
            addUserMessage(message);
            disableInput();
            await getResponse(message);
            enableInput();
        }
    }

    sendButton.addEventListener('click', sendMessage);
    userInput.addEventListener('keydown', (event) => {
        if (event.key === 'Enter') {
            sendMessage()
        }
    });
</script>
</body>
</html>
